package com.tarena.lbs.activity.config;

import com.tarena.lbs.common.constant.AmqpDeclareConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 *这个配置类专门声明业务所需组件用的
 *声明一个路由交换机 Direct direct_near_stores_ex
 *声明一个普通队列 Queue near_stores_queue
 *确定绑定关系 near_stores_rk做路由key值绑定
 */
@Configuration
@Slf4j
public class DeclareConfiguration {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        return rabbitTemplate;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }

    @Bean
    public Exchange declareDirectExchange(){
        log.info("声明交换机");
        return new DirectExchange(AmqpDeclareConst.NEAR_STORES_EX,true,false);
    }

    @Bean
    public Queue declareQueue(){
        log.info("声明队列");
        Queue queue = new Queue(AmqpDeclareConst.NEAR_STORES_QUEUE,true,false,false);
        return queue;
    }

    @Bean
    public Binding declareBinding(){
        log.info("声明绑定关系");
        Map<String,Object> headers=new HashMap<>();
        return BindingBuilder.bind(declareQueue()).to(declareDirectExchange())
                .with(AmqpDeclareConst.NEAR_STORES_RK).and(headers);
    }

}
